<?php

namespace App\Http\Controllers\Api;

use App\Interface\CurdController;
use App\Librarys\Message;
use App\Models\ContentSimpleModel;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ContentSimplecontroller extends BaseController implements CurdController
{
    protected Request $request;
    protected Model $contentSimpleModel;

    public function __construct(Request $request, ContentSimpleModel $contentSimpleModel)
    {
        $this->request = $request;
        $this->contentSimpleModel = $contentSimpleModel;
    }

    public function create()
    {
        // 获取操作类型
        $flag = $this->request->flag;
        // 获取基础信息
        $simple['title'] = $this->request->title;
        $simple['cid'] = $this->request->cid;
        $simple['type'] = $this->request->type;
        $simple['description'] = $this->request->description;
        $simple['thumbnail'] = $this->request->thumbnail;
        $simple['author'] = Auth::guard('api')->user()->uid;
        $simple['is_banner'] = $this->request->is_banner;
        $simple['is_recommend'] = $this->request->is_recommend;

        // 获取内容详情
        $detail['content'] = $this->request->content;
        // 判断是否有描述，自动生成描述
        if($simple['description'] == '') {
            // 去除正文html标签
            $tmpContent = strip_tags($detail['content']);
            // 截取前250字
            $simple['description'] = mb_substr($tmpContent, 0, 140);
        }

        // 匹配操作
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'create': // 新增操作

                $simple['like'] = mt_rand(10, 100);
                $simple['click'] = mt_rand(1000, 90000);
                // 验证基础数据
                $simpleValidate = Validator::make($simple, [
                    'title' => 'required',
                    'cid' => 'required',
                    'type' => 'required',
                    'like' => 'required',
                    'click' => 'required',
                    'author' => 'required'
                ], [
                    'title.required' => '内容标题不能为空',
                    'cid.required' => '内容分类不能为空',
                    'type.required' => '内容类型不能为空',
                    'description.required' => '内容描述不能为空',
                    'like.required' => '内容点赞不能为空',
                    'click.required' => '内容点击不能为空',
                    'author.required' => '内容作者不能为空',
                ]);

                // 判断验证
                if ($simpleValidate->fails()) { // 验证失败
                    return Message::show(false, $simpleValidate->errors()->first());
                }

                // 验证通过，开启事务
                DB::beginTransaction();
                try {
                    // 尝试写入基础信息
                    $simpleInfo = $this->contentSimpleModel->create($simple);
                    // 组装详细信息
                    $detail['cs_id'] = $simpleInfo->cs_id;
                    // 尝试写入详细信息
                    $simpleInfo->content_detail()->create($detail);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '内容发布成功');
                } catch (Exception $error) {
                    // 事务回滚
                    DB::rollBack();
                    return Message::show(false, '内容发布失败：' . $error->getMessage());
                }
                break;
            case 'update': // 修改操作
                // 获取操作ID
                $cs_id = $this->request->cs_id;
                $simple['like'] = $this->request->like;
                $simple['click'] = $this->request->click;
                // 验证基础数据
                $simpleValidate = Validator::make($simple, [
                    'title' => 'required',
                    'cid' => 'required',
                    'type' => 'required',
                    'like' => 'required',
                    'click' => 'required',
                    'author' => 'required'
                ], [
                    'title.required' => '内容标题不能为空',
                    'cid.required' => '内容分类不能为空',
                    'type.required' => '内容类型不能为空',
                    'description.required' => '内容描述不能为空',
                    'author.required' => '内容作者不能为空',
                ]);

                // 判断验证
                if ($simpleValidate->fails()) { // 验证失败
                    return Message::show(false, $simpleValidate->errors()->first());
                }

                // 验证通过，开启事务
                DB::beginTransaction();
                try {
                    // 尝试写入基础信息
                    $simpleInfo = $this->contentSimpleModel->where(['cs_id' => $cs_id])->first();
                    $simpleInfo->update($simple);
                    // 尝试写入详细信息
                    $simpleInfo->content_detail()->update($detail);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '内容修改成功');
                } catch (Exception $error) {
                    // 事务回滚
                    DB::rollBack();
                    return Message::show(false, '内容修改失败：' . $error->getMessage());
                }
                break;
        }
    }

    public function query()
    {
        // 获取操作标准
        $flag = $this->request->flag;

        // switch匹配对应格式数据
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'table':   // 获取用户列表用于后台表格展示
                // 获取分页数据
                $page = $this->request->page;
                $size = $this->request->size;
                $start  = ($page - 1) * $size;

                // 获取用户总数
                $contentList['total'] = $this->contentSimpleModel->count();
                $contentList['page'] = (int)$page;
                $contentList['size'] = (int)$size;

                // 获取当前列表数据
                $contents = $this->contentSimpleModel->limit($size)->skip($start)->with(['category', 'content_detail'])->orderBy('cs_id', 'desc')->get();
                $contentList['list'] = $contents;
                return Message::show(true, '获取成功', $contentList);
                break;
            case 'new': // 获取最新主题
                // 获取显示数量
                $num = $this->request->num;
                // 获取内容
                $randContent = $this->contentSimpleModel->where('created_at', '>=', Carbon::now()->subDays(30))->limit($num)->orderBy('created_at', 'desc')->get();
                return Message::show(true, '获取成功', $randContent);
                break;
            case 'detail': // 获取详情
                // 获取主键
                $cs_id = $this->request->cs_id;
                // 获取主题详情
                $contentDetail = $this->contentSimpleModel->where(['cs_id' => $cs_id])->with(['content_detail', 'user'])->first();
                return Message::show(true, '获取成功', $contentDetail);
                break;
            case 'recommend': // 获取推荐
                // 获取数量
                $num = $this->request->num;
                $recommendContent = $this->contentSimpleModel->where(['is_recommend' => 1])->limit($num)->get();
                return Message::show(true, '获取成功', $recommendContent);
                break;
            case 'previous': // 获取前N条
                // 获取当前ID
                $cs_id = $this->request->cs_id;
                // 获取条数
                $num = $this->request->num;
                // 获取数据
                $previousContent = $this->contentSimpleModel->where('cs_id', '<=', $cs_id)->limit($num)->orderBy('cs_id', 'desc')->get();
                return Message::show(true, '获取成功', $previousContent);
        }
    }

    public function delete()
    {
    }
}
